package com.baijiayun.live.ui.speakerlist.item;

import android.app.Activity;
import android.app.Dialog;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.annotation.ColorInt;
import androidx.annotation.StringRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.baijiayun.glide.Glide;
import com.baijiayun.live.ui.LiveSDKWithUI;
import com.baijiayun.live.ui.R;
import com.baijiayun.live.ui.activity.LiveRoomRouterListener;
import com.baijiayun.live.ui.utils.QueryPlus;
import com.baijiayun.live.ui.utils.VideoDefinitionUtil;
import com.baijiayun.livecore.context.LPConstants;
import com.baijiayun.livecore.context.LiveRoom;
import com.baijiayun.livecore.models.imodels.IMediaModel;
import com.baijiayun.livecore.models.imodels.IUserModel;
import com.baijiayun.livecore.utils.CommonUtils;
import com.baijiayun.livecore.viewmodels.impl.LPSpeakQueueViewModel;
import com.baijiayun.livecore.wrapper.LPPlayer;
import com.baijiayun.livecore.wrapper.impl.LPVideoView;
import com.baijiayun.livecore.wrapper.listener.LPRTMPPlayerListener;
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Shubo on 2019-07-25.
 */
public class RemoteItem extends BaseSwitchItem implements Playable, LifecycleObserver {

    private QueryPlus $;
    protected Activity context;
    protected LPPlayer player;
    protected LiveRoom liveRoom;
    private LPVideoView videoView;
    protected IMediaModel mediaModel;
    protected SpeakItemType itemType;
    private ViewGroup itemContainer;
    protected ViewGroup container;
    private ImageView avatarImageView;
    protected FrameLayout videoContainer;
    protected Animation loadingViewAnimation;
    protected LoadingListener loadingListener;
    protected ViewGroup loadingContainer;
    protected ImageView loadingImageView;
    private boolean isZOrderMediaOverlay = true;
    protected Dialog dialog;
    private LPConstants.LPCDNResolution cdnResolution = null;
    private boolean isMaxInScreen;

    private boolean isVideoPlaying, isAudioPlaying, isVideoClosedByUser;
    protected static FrameLayout.LayoutParams layoutParams =
            new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

    public RemoteItem(ViewGroup itemContainer, IMediaModel mediaModel, LiveRoomRouterListener routerListener) {
        super(routerListener);
        this.mediaModel = mediaModel;
        this.itemContainer = itemContainer;
        this.context = (Activity) itemContainer.getContext();
        liveRoom = routerListener.getLiveRoom();
        player = liveRoom.getPlayer();
        status = SwitchableStatus.SpeakList;
        refreshItemType();
        initView();
    }

    public void refreshItemType() {
        if (liveRoom.getSpeakQueueVM().isMixModeOn()) {
            if (LPSpeakQueueViewModel.FAKE_MIX_STREAM_USER_ID.equals(mediaModel.getUser().getUserId())) {
                itemType = SpeakItemType.Presenter;
            } else if (mediaModel.isVideoOn() && !isVideoClosedByUser) {
                itemType = SpeakItemType.Video;
            } else {
                itemType = SpeakItemType.Audio;
            }
        } else {
            if (liveRoom.getPresenterUser() != null && mediaModel.getUser().getUserId().equals(liveRoom.getPresenterUser().getUserId())) {
                itemType = SpeakItemType.Presenter;
            } else if (mediaModel.isVideoOn() && !isVideoClosedByUser) {
                itemType = SpeakItemType.Video;
            } else {
                itemType = SpeakItemType.Audio;
            }
        }
    }

    protected void initView() {
        container = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.bjy_item_view_speaker_remote, itemContainer, false);
        $ = QueryPlus.with(container);
        videoContainer = (FrameLayout) $.id(R.id.item_speak_speaker_avatar_container).view();
        avatarImageView = new ImageView(context);
        avatarImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        loadingContainer = (ViewGroup) $.id(R.id.item_speak_speaker_loading_container).view();
        loadingImageView = (ImageView) $.id(R.id.item_speak_speaker_loading_img).view();
        refreshNameTable();
        if (!TextUtils.isEmpty(mediaModel.getUser().getAvatar())) {
            String avatar = mediaModel.getUser().getAvatar().startsWith("//") ? "https:" + mediaModel.getUser().getAvatar() : mediaModel.getUser().getAvatar();
            Glide.with(context).load(avatar).into(avatarImageView);
            videoContainer.addView(avatarImageView);
        }
        $.id(R.id.item_speak_speaker_video_label).visibility(mediaModel.isVideoOn() ? View.VISIBLE : View.GONE);
        container.setTag(R.id.lp_speaker_audio_type_tag, mediaModel.getUser().getUserId());
        registerClickEvent($.contentView());
        if (liveRoom != null && liveRoom.isTeacherOrAssistant() && mediaModel.getUser().getType() == LPConstants.LPUserType.Student) {
            $.id(R.id.item_speak_speaker_award_count_tv).clicked(v -> routerListener.requestAward(mediaModel.getUser()));
        }
    }

    public void refreshNameTable() {
        String userName = CommonUtils.getEncodePhoneNumber(mediaModel.getUser().getName());
        if (itemType == SpeakItemType.Presenter) {
            String teacherLabel = liveRoom.getCustomizeTeacherLabel();
            teacherLabel = TextUtils.isEmpty(teacherLabel) ? context.getString(R.string.live_teacher_hint) : "(" + teacherLabel + ")";
            $.id(R.id.item_speak_speaker_name).text(userName + (mediaModel.getUser().getType() == LPConstants.LPUserType.Teacher ? teacherLabel : context.getString(R.string.live_presenter_hint)));
        } else if (mediaModel.getUser().getType() == LPConstants.LPUserType.Teacher) {
            String teacherLabel = liveRoom.getCustomizeTeacherLabel();
            teacherLabel = TextUtils.isEmpty(teacherLabel) ? context.getString(R.string.live_teacher_hint) : "(" + teacherLabel + ")";
            $.id(R.id.item_speak_speaker_name).text(userName + teacherLabel);
        } else if (mediaModel.getUser().getType() == LPConstants.LPUserType.Assistant) {
            String assistantLabel = liveRoom.getCustomizeAssistantLabel();
            assistantLabel = TextUtils.isEmpty(assistantLabel) ? "" : "(" + assistantLabel + ")";
            $.id(R.id.item_speak_speaker_name).text(userName + (TextUtils.isEmpty(assistantLabel) ? "" : assistantLabel));
        } else
            $.id(R.id.item_speak_speaker_name).text(userName);
    }

    @Override
    public void refreshPlayable() {
        if (mediaModel.isVideoOn() && !isVideoClosedByUser) {
            stopStreaming();
            streamVideo();
        } else if (mediaModel.isAudioOn()) {
            stopStreaming();
            streamAudio();
        } else {
            stopStreaming();
        }
    }


    @Override
    public void refreshPlayable(boolean videoOn, boolean audioOn) {
        // do nothing
    }

    @Override
    public IUserModel getUser() {
        return mediaModel.getUser();
    }

    @Override
    public void notifyAwardChange(int count) {
        if (count > 0) {
            $.id(R.id.item_speak_speaker_award_count_tv).visibility(View.VISIBLE);
            $.id(R.id.item_speak_speaker_award_count_tv).text(String.valueOf(count));
        }
    }

    @Override
    public boolean hasVideo() {
        return mediaModel.isVideoOn();
    }

    public void setZOrderMediaOverlay(boolean ZOrderMediaOverlay) {
        isZOrderMediaOverlay = ZOrderMediaOverlay;
    }

    @Override
    public boolean hasAudio() {
        return mediaModel.isAudioOn();
    }

    @Override
    public boolean isVideoStreaming() {
        return isVideoPlaying;
    }

    @Override
    public boolean isAudioStreaming() {
        return isAudioPlaying;
    }

    @Override
    public boolean isStreaming() {
        return isAudioPlaying || isVideoPlaying;
    }

    private void streamAudio() {
        player.playAudio(mediaModel.getMediaId());
        isAudioPlaying = true;
    }

    private void streamVideo() {
        if (videoView == null) {
            videoView = new LPVideoView(context.getApplicationContext());
            videoView.setAspectRatio(LPConstants.LPAspectRatio.Fit);
        }
        videoView.setZOrderMediaOverlay(isZOrderMediaOverlay);
        videoContainer.removeAllViews();
        videoContainer.addView(videoView, layoutParams);

        showLoading();

        player.playVideo(mediaModel.getMediaId(), videoView);
        isAudioPlaying = true;
        isVideoPlaying = true;
        showVideoOpen();
    }

    private void showLoading() {
        if (loadingListener == null) {
            loadingListener = new LoadingListener(this);
            player.addPlayerListener(loadingListener);
        }
        loadingContainer.setVisibility(View.VISIBLE);
        if (loadingViewAnimation == null) {
            loadingViewAnimation = AnimationUtils.loadAnimation(context, R.anim.live_video_loading);
            loadingViewAnimation.setInterpolator(new LinearInterpolator());
        }
        loadingImageView.startAnimation(loadingViewAnimation);
    }

    protected void hideLoading() {
        loadingContainer.setVisibility(View.GONE);
        if (loadingViewAnimation != null) {
            loadingViewAnimation.cancel();
        }
        loadingImageView.clearAnimation();
    }

    @Override
    public void switchToMaxScreen() {
        super.switchToMaxScreen();
        if (videoView != null) {
            videoView.setZOrderMediaOverlay(false);
        }
        hideNickName(true);
    }

    @Override
    public void switchToSpeakList() {
        super.switchToSpeakList();
        if (videoView != null) {
            videoView.setZOrderMediaOverlay(true);
        }
        hideNickName(false);
    }

    @Override
    public void switchToMainScreen() {
        super.switchToMainScreen();
        if (videoView != null) {
            videoView.setZOrderMediaOverlay(true);
        }
        hideNickName(false);
    }

    @Override
    public void switchToFullScreen(boolean isFullScreen) {
        super.switchToFullScreen(isFullScreen);
        if (videoView != null) {
            videoView.setZOrderMediaOverlay(true);
        }
        if (isFullScreen) {
            hideNickName(true);
        }
    }


    protected void hideNickName(boolean hide) {
        isMaxInScreen = hide;
    }

    @Override
    public SwitchableType getSwitchableType() {
        return SwitchableType.SpeakItem;
    }

    @Override
    public void stopStreaming() {
        hideLoading();
        player.playAVClose(mediaModel.getMediaId());
        isVideoPlaying = false;
        isAudioPlaying = false;
        showVideoClose();
    }

    protected void showVideoClose() {
        videoContainer.removeAllViews();
        videoContainer.addView(avatarImageView, layoutParams);
        $.id(R.id.item_speak_speaker_video_label).visibility(hasVideo() ? View.VISIBLE : View.GONE);
    }

    protected void showVideoOpen() {
        $.id(R.id.item_speak_speaker_video_label).visibility(View.GONE);
    }

    @Override
    public String getIdentity() {
        if (mediaModel.getMediaSourceType() == LPConstants.MediaSourceType.ExtCamera
                || mediaModel.getMediaSourceType() == LPConstants.MediaSourceType.ExtScreenShare
                || mediaModel.getMediaSourceType() == LPConstants.MediaSourceType.ExtMedia) {
            return mediaModel.getUser().getUserId() + "_1";
        }
        return mediaModel.getUser().getUserId();
    }

    @Override
    public SpeakItemType getItemType() {
        return itemType;
    }

    @Override
    public View getView() {
        return container;
    }

    public void setMediaModel(IMediaModel mediaModel) {
        this.mediaModel = mediaModel;
        refreshItemType();
    }

    public void updateNetworkState(String status, @ColorInt int color) {
        $.id(R.id.item_speak_speaker_network).text(status);
        ((TextView) $.id(R.id.item_speak_speaker_network).view()).setTextColor(color);
    }

    public boolean isVideoClosedByUser() {
        return isVideoClosedByUser;
    }

    public void setVideoCloseByUser(boolean isVideoClosedByUser) {
        this.isVideoClosedByUser = isVideoClosedByUser;
    }

    @Override
    public void showOptionDialog() {
        List<String> options = new ArrayList<>();
        if (isInFullScreen()) {
            options.add(getString(R.string.live_full_screen_exit));
        } else {
            //坐席区为了兼容iOS，暂时不加全屏选项
            if (getSwitchableType() == SwitchableType.MainItem) {
                options.add(getString(R.string.live_full_screen));
            }
        }
        if (canSwitchPPTAndMainVideo() && !isInFullScreen() && status != SwitchableStatus.MaxScreen) {
            options.add(getString(R.string.live_max_screen));
        }
        switch (itemType) {
            case Presenter:
                if (mediaModel.isVideoOn() || mediaModel.isAudioOn()) {
                    if (isVideoPlaying) {
                        if (mediaModel.getVideoDefinitions().size() > 1) {
                            options.add(getString(R.string.live_switch_definitions));
                        }
                        if (liveRoom.isClassStarted()) {
                            options.add(getString(R.string.live_close_video));
                        }

                    } else if (mediaModel.isVideoOn() && !isVideoPlaying) {
                        if (liveRoom.isClassStarted()) {
                            options.add(getString(R.string.live_open_video));
                        }
                    }
                    if (canCurrentUserSetPresenter() && mediaModel.getUser().getType() == LPConstants.LPUserType.Assistant) {
                        options.add(getString(R.string.live_unset_presenter));
                    }
                    if (enableShowResolutionText()) {
                        options.add(getString(R.string.bjy_live_cdn_resolution_original));
                        options.add(getString(R.string.bjy_live_cdn_resolution_high));
                    }
                }
                break;
            case Video:
                if (canCurrentUserSetPresenter() && isThisTeacherOrAssistant()) {
                    options.add(getString(R.string.live_set_to_presenter));
                }
                if (mediaModel.getUser().getType() == LPConstants.LPUserType.Student && liveRoom.isTeacherOrAssistant()) {
                    if (liveRoom.getPartnerConfig().liveDisableGrantStudentBrush != 1) {
                        if (liveRoom.getSpeakQueueVM().getStudentsDrawingAuthSet().contains(mediaModel.getUser().getNumber())) {
                            options.add(getString(R.string.live_unset_auth_drawing));
                        }
                        else {
                            options.add(getString(R.string.live_set_auth_drawing));
                        }
                    }
                }
                if (mediaModel.getVideoDefinitions().size() > 1) {
                    options.add(getString(R.string.live_switch_definitions));
                }
                if (liveRoom.isTeacherOrAssistant() && mediaModel.getUser().getType() == LPConstants.LPUserType.Student) {
                    options.add(getString(R.string.live_award));
                }
                if (liveRoom.isClassStarted()) {
                    options.add(getString(R.string.live_close_video));
                }
                if(liveRoom.isUseWebRTC() && liveRoom.getPartnerConfig().enableSwitchMirrorMode && liveRoom.isTeacherOrAssistant()) {
                    options.add(getString(R.string.bjy_live_horizon_mirror));
                    options.add(getString(R.string.bjy_live_vertical_mirror));
                }
                if (liveRoom.isTeacherOrAssistant() && liveRoom.getRoomType() == LPConstants.LPRoomType.Multi && mediaModel.getUser().getType() != LPConstants.LPUserType.Teacher) {
                    options.add(getString(R.string.live_close_speaking));
                }
                break;
            case Audio:
                if (mediaModel.isVideoOn() && liveRoom.isClassStarted()) {
                    options.add(getString(R.string.live_open_video));
                }
                if (canCurrentUserSetPresenter() && (mediaModel.getUser().getType() == LPConstants.LPUserType.Teacher || mediaModel.getUser().getType() == LPConstants.LPUserType.Assistant)) {
                    options.add(getString(R.string.live_set_to_presenter));
                }
                if (mediaModel.getUser().getType() == LPConstants.LPUserType.Student && liveRoom.isTeacherOrAssistant()) {
                    if (liveRoom.getPartnerConfig().liveDisableGrantStudentBrush != 1) {
                        if (liveRoom.getSpeakQueueVM().getStudentsDrawingAuthSet().contains(mediaModel.getUser().getNumber())) {
                            options.add(getString(R.string.live_unset_auth_drawing));
                        }
                        else {
                            options.add(getString(R.string.live_set_auth_drawing));
                        }
                    }
                }
                if (liveRoom.isTeacherOrAssistant() && liveRoom.getRoomType() == LPConstants.LPRoomType.Multi && mediaModel.getUser().getType() != LPConstants.LPUserType.Teacher) {
                    options.add(getString(R.string.live_close_speaking));
                }
                break;
            default:
                break;
        }

        if (options.size() <= 0) return;
        if (context.isFinishing()) return;
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new ThemeMaterialDialogBuilder(context)
                .items(options)
                .itemsCallback((materialDialog, view, i, charSequence) -> {
                    if (context.isFinishing() || context.isDestroyed()) return;
                    if (getString(R.string.live_close_video).equals(charSequence.toString())) {
                        stopStreaming();
                        streamAudio();
                        isVideoClosedByUser = true;
                        if (getSwitchableType() != SwitchableType.PPT) {
                            if (isInFullScreen()) {
                                switchToFullScreen(false);
                            } else {
                                routerListener.handleUserCloseAction(this);
                            }
                        }
                        refreshItemType();
                    } else if (getString(R.string.live_close_speaking).equals(charSequence.toString())) {
                        liveRoom.getSpeakQueueVM().closeOtherSpeak(mediaModel.getUser().getUserId());
                    } else if (getString(R.string.live_open_video).equals(charSequence.toString())) {
                        stopStreaming();
                        streamVideo();
                        isVideoClosedByUser = false;
                        if (!isInFullScreen()) {
                            routerListener.handleUserCloseAction(this);
                        }
                        refreshItemType();
                    } else if (getString(R.string.live_max_screen).equals(charSequence.toString())) {
                        if (!canSwitchPPTAndMainVideo()) {
                            return;
                        }
                        switchPPTVideoSync();
                    } else if (getString(R.string.live_switch_definitions).equals(charSequence.toString())) {
                        showVideoDefinitionSwitchDialog();
                    } else if (getString(R.string.live_set_to_presenter).equals(charSequence.toString())) {
                        liveRoom.getSpeakQueueVM().requestSwitchPresenter(mediaModel.getUser().getUserId());
                        refreshItemType();
                    } else if (getString(R.string.live_unset_presenter).equals(charSequence.toString())) {
                        liveRoom.getSpeakQueueVM().requestSwitchPresenter(liveRoom.getCurrentUser().getUserId());
                        refreshItemType();
                    } else if (getString(R.string.live_set_auth_drawing).equals(charSequence.toString())) {
                        liveRoom.getSpeakQueueVM().requestStudentDrawingAuthChange(true, mediaModel.getUser().getNumber());
                    } else if (getString(R.string.live_unset_auth_drawing).equals(charSequence.toString())) {
                        liveRoom.getSpeakQueueVM().requestStudentDrawingAuthChange(false, mediaModel.getUser().getNumber());
                    } else if (getString(R.string.live_award).equals(charSequence.toString())) {
                        routerListener.requestAward(mediaModel.getUser());
                    } else if (getString(R.string.live_full_screen).equals(charSequence.toString())) {
                        switchToFullScreen(true);
                    } else if (getString(R.string.live_full_screen_exit).equals(charSequence.toString())) {
                        switchToFullScreen(false);
                    } else if (getString(R.string.bjy_live_horizon_mirror).equals(charSequence.toString())) {
                        boolean horizonMirror = liveRoom.getSpeakQueueVM().getHorizontalMirrorModeSet().contains(mediaModel.getUser().getNumber());
                        boolean verticalMirror = liveRoom.getSpeakQueueVM().getVerticalMirrorModeSet().contains(mediaModel.getUser().getNumber());
                        liveRoom.getSpeakQueueVM().requestMirrorModeSwitch(mediaModel.getUser().getNumber(), mediaModel.getUser().getUserId(), !horizonMirror, verticalMirror);
                    } else if (getString(R.string.bjy_live_vertical_mirror).equals(charSequence.toString())) {
                        boolean horizonMirror = liveRoom.getSpeakQueueVM().getHorizontalMirrorModeSet().contains(mediaModel.getUser().getNumber());
                        boolean verticalMirror = liveRoom.getSpeakQueueVM().getVerticalMirrorModeSet().contains(mediaModel.getUser().getNumber());
                        liveRoom.getSpeakQueueVM().requestMirrorModeSwitch(mediaModel.getUser().getNumber(), mediaModel.getUser().getUserId(), horizonMirror, !verticalMirror);
                    } else if (getString(R.string.bjy_live_cdn_resolution_high).equals(charSequence.toString())) {
                        setCDNResolution(LPConstants.LPCDNResolution.HIGH);
                    } else if (getString(R.string.bjy_live_cdn_resolution_original).equals(charSequence.toString())) {
                        setCDNResolution(LPConstants.LPCDNResolution.ORIGINAL);
                    }
                    materialDialog.dismiss();
                })
                .show();
    }

    protected void showVideoDefinitionSwitchDialog() {
        if (mediaModel.getVideoDefinitions().size() <= 1) return;
        List<String> options = new ArrayList<>();
        for (LPConstants.VideoDefinition definition : mediaModel.getVideoDefinitions()) {
            options.add(VideoDefinitionUtil.getVideoDefinitionLabelFromType(definition));
        }
        if (context.isDestroyed() || context.isFinishing()) return;
        new ThemeMaterialDialogBuilder(context)
                .items(options)
                .itemsCallback((dialog, itemView, position, text) -> {
                    if (position == -1) return;
                    LPConstants.VideoDefinition definition = VideoDefinitionUtil.getVideoDefinitionTypeFromLabel(text.toString());
                    if (definition == null) return;
                    liveRoom.getPlayer().changeVideoDefinition(mediaModel.getUser().getUserId(), definition);
                    dialog.dismiss();
                })
                .show();
    }

    protected String getString(@StringRes int resId) {
        return context.getString(resId);
    }

    protected boolean canCurrentUserSetPresenter() {
        return liveRoom.getPartnerConfig().isEnableSwitchPresenter == 1 && (liveRoom.getCurrentUser().getType() == LPConstants.LPUserType.Teacher || (liveRoom.getPartnerConfig().enableAssistantTurnPresenter && liveRoom.getCurrentUser().getType() == LPConstants.LPUserType.Assistant && liveRoom.getSpeakQueueVM().isPresenterUser(liveRoom.getCurrentUser())));
    }

    public LPConstants.MediaSourceType getMediaSourceType() {
        return mediaModel.getMediaSourceType();
    }

    protected boolean isThisTeacherOrAssistant() {
        return mediaModel.getUser().getType() == LPConstants.LPUserType.Teacher || mediaModel.getUser().getType() == LPConstants.LPUserType.Assistant;
    }

    public void hideWaterMark() {
        if (videoView != null)
            videoView.setWaterMarkVisibility(View.INVISIBLE);
    }

    public void showWaterMark() {
        if (videoView != null) {
            videoView.setWaterMarkVisibility(View.VISIBLE);
        }
    }

    protected void setCDNResolution(LPConstants.LPCDNResolution resolution) {
        if (cdnResolution == null || cdnResolution != resolution) {
            cdnResolution = resolution;
            player.setCDNResolution(cdnResolution);
            refreshPlayable();
            setCDNResolutionText(cdnResolution == LPConstants.LPCDNResolution.ORIGINAL ?
                    getString(R.string.bjy_live_cdn_resolution_original) : getString(R.string.bjy_live_cdn_resolution_high), isMaxInScreen);
        }
    }

    //三分频重载用于判断是否是右上角老师区
    public boolean isPresenterVideo() {
        return false;
    }

    /**
     * keep_alive=true, 即使关闭音视频仍然保留席位
     * 1v1只需要保留学生，主讲是必保留的
     * @return
     */
    public boolean isKeepAlive() {
        return mediaModel.isKeepAlive() || (liveRoom.getRoomType() == LPConstants.LPRoomType.OneOnOne && mediaModel.getUser().getType() == LPConstants.LPUserType.Student);
    }


    public static class LoadingListener extends LPRTMPPlayerListener {
        private WeakReference<RemoteItem> remoteItemWeakReference;

        public LoadingListener(RemoteItem remoteItem) {
            remoteItemWeakReference = new WeakReference<>(remoteItem);
        }

        @Override
        public void onReadyToPlay(String mediaId) {
            // webrtc辅助摄像头屏幕分享mediaID为uid_3 大班课里辅助摄像头/辅助摄像头屏幕分享都识别为uid_1
            if (mediaId.endsWith("_3")) {
                mediaId = mediaId.replace("_3", "_1");
            } else if (mediaId.endsWith("_5")) {
                mediaId = mediaId.replace("_5", "_1");
            }
            RemoteItem remoteItem = remoteItemWeakReference.get();
            if (remoteItem == null || !remoteItem.getIdentity().equals(mediaId)) return;
            remoteItem.hideLoading();
            remoteItem.onReadyToPlay(mediaId);
        }

        @Override
        public void onStreamConnectionChange(String mediaId, boolean isConnected) {
            // webrtc辅助摄像头屏幕分享mediaID为uid_3 大班课里辅助摄像头/辅助摄像头屏幕分享都识别为uid_1
            if (mediaId.endsWith("_3")) {
                mediaId = mediaId.replace("_3", "_1");
            } else if (mediaId.endsWith("_5")) {
                mediaId = mediaId.replace("_5", "_1");
            }
            RemoteItem remoteItem = remoteItemWeakReference.get();
            if (remoteItem == null || !remoteItem.getIdentity().equals(mediaId)) return;
            if (isConnected) {
                remoteItem.hideLoading();
            } else {
                remoteItem.showLoading();
            }
        }

        @Override
        public void onPlayComplete(String mediaId) {
            RemoteItem remoteItem = remoteItemWeakReference.get();
            if (remoteItem == null || !remoteItem.getIdentity().equals(mediaId)){
                return;
            }
            remoteItem.onPlayComplete(mediaId);
        }

        @Override
        public void onBufferingUpdate(String mediaId, int percent) {
            RemoteItem remoteItem = remoteItemWeakReference.get();
            if (remoteItem == null || !remoteItem.getIdentity().equals(mediaId)){
                return;
            }
            remoteItem.onBufferingUpdate(mediaId, percent);
        }

        @Override
        public void onSeekComplete(String mediaId) {
            // do nothing
        }
    }

    protected boolean enableShowResolutionText() {
        return !liveRoom.getSpeakQueueVM().isPresenterUser(liveRoom.getCurrentUser())
                && liveRoom.getPartnerConfig().liveEnableSwitchCdnResolution
                && (liveRoom.getSpeakQueueVM().isMixModeOn() || !liveRoom.isUseWebRTC())
                && !mediaModel.isWarmingUpVideo();
    }

    protected void onReadyToPlay(String mediaId) {
        // do nothing
    }

    protected void onPlayComplete(String mediaId) {
        // do nothing
    }

    protected void onBufferingUpdate(String mediaId, int percent) {
        // do nothing
    }

    protected void setCDNResolutionText(String resolutionText, boolean isMaxInScreen) {
        // do nothing
    }


    protected boolean attachVideoOnResume, attachAudioOnResume;

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        if (LiveSDKWithUI.isAudioBackOpen)
            return;
        if (attachVideoOnResume) {
            streamVideo();
            attachVideoOnResume = false;
            attachAudioOnResume = false;
            return;
        }
        if (attachAudioOnResume) {
            streamAudio();
            attachAudioOnResume = false;
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        if (LiveSDKWithUI.isAudioBackOpen)
            return;
        attachAudioOnResume = isAudioStreaming();
        attachVideoOnResume = isVideoStreaming();
        stopStreaming();
    }
}
